﻿#ifndef SHAREDMEMORYIMPL_H
#define SHAREDMEMORYIMPL_H

#include <string>
#include <memory>

#include "SystemSemaphore.h"

class SharedMemoryImpl
{
public:
    static std::shared_ptr<SharedMemoryImpl> CreateImpl(const std::string &key);

    virtual bool Create(size_t size) = 0;
    virtual bool Attach(int permissions) = 0;
    virtual bool Detach() = 0;
    virtual bool IsAttached() const = 0;

    virtual int Write(unsigned char *data, size_t size) = 0;
    virtual int Read(unsigned char *buf, size_t size) = 0;

    inline void Lock()
    {
        if (sem)
            sem->Acquire();
    }

    inline void Unlock()
    {
        if (sem)
            sem->Release();
    }

    inline void *GetData() const
    {
        return memory;
    }

    inline int GetDataSize() const
    {
        return size;
    }

protected:
    explicit SharedMemoryImpl(const std::string &key)
        : key(key)
    {
        auto sem_key = key + "%Semaphore%";
        sem = std::make_shared<SystemSemaphore>(sem_key, 1, SystemSemaphore::Create);
    }
    virtual ~SharedMemoryImpl() = default;

protected:
    void *memory{nullptr};
    int size{0};
    std::string key;
    std::shared_ptr<SystemSemaphore> sem{nullptr};
};

#endif // SHAREDMEMORYIMPL_H
